package com.hao.wms.service.impl;

import com.hao.wms.dao.IOrderBillDao;
import com.hao.wms.domain.OrderBill;
import com.hao.wms.domain.OrderBillItem;
import com.hao.wms.query.PageResult;
import com.hao.wms.query.QueryObject;
import com.hao.wms.service.IOrderBillService;
import com.hao.wms.util.UserContext;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

public class OrderBillServiceImpl implements IOrderBillService {
    private IOrderBillDao dao;


    public void setDao(IOrderBillDao dao) {
        this.dao = dao;
    }

    @Override
    public void save(OrderBill orderBill) {
        //1.设置制单人和制单时间
        orderBill.setInputUser(UserContext.getUser());
        orderBill.setInputTime(new Date());
        //2.手动设置单据的未审核状态
        orderBill.setStatus(OrderBill.NORMAL);
        parseItems(orderBill);
        //6.保存单据
        dao.save(orderBill);

    }

    private void parseItems(OrderBill orderBill) {
        orderBill.setTotalNumber(BigDecimal.ZERO);
        orderBill.setTotalAmount(BigDecimal.ZERO);
        for (OrderBillItem item : orderBill.getItems()) {
            //3.处理单据和明细的关系
            item.setBill(orderBill);
            //4.计算单条明细的小计
            item.setAmount(item.getCostPrice().multiply(item.getNumber()).setScale(2, BigDecimal.ROUND_HALF_UP));
            //5.计算单据的总数量和总金额
            orderBill.setTotalNumber(orderBill.getTotalNumber().add(item.getNumber()));
            orderBill.setTotalAmount(orderBill.getTotalAmount().add(item.getAmount()));
        }
    }

    @Override
    public void update(OrderBill orderBill) {
        if (orderBill.getStatus() == OrderBill.NORMAL) {
            parseItems(orderBill);
            dao.update(orderBill);
        }

    }

    @Override
    public void delete(OrderBill orderBill) {
        dao.delete(orderBill);

    }

    @Override
    public void audit(Long id) {
        OrderBill bill = dao.get(id);
        if(bill.getStatus()==OrderBill.NORMAL){
            bill.setStatus(OrderBill.AUDIT);
            bill.setAuditor(UserContext.getUser());
            bill.setAuditTime(new Date());
            dao.update(bill);
        }
    }

    @Override
    public OrderBill get(Long id) {
        return dao.get(id);
    }

    @Override
    public List<OrderBill> list() {
        return dao.list();
    }

    @Override
    public PageResult query(QueryObject qo) {
        return dao.query(qo);
    }


}
